<?php

class TestController extends Controller
{
	public function actionIndex()
	{
		$model = new User;
		
		$this->render('index',
			array(
				'test1' => 'Hello world',
				'model' => $model
			)
		);
	}
	
	public function actionCreate()
    {
        $model = new User;

        $this -> performAjaxValidation($model);
        
        if (Yii::app()->request->isAjaxRequest) {
            $model->attributes = $_POST['User'];            
            if ($model->save()) {
                echo CJSON::encode(array(
                    'status' => 'success'                      
                ));
            } else {
                echo CJSON::encode(array(
                    'status' => 'failure'
                ));
            }
        }
        else
        {
            echo CJSON::encode(array(
                'status' => 'failure'
            ));
        }
    }
	
	protected function performAjaxValidation($model)
	{
            $err = CActiveForm::validate($model);

            if($err != "[]")
            {
                echo $err;
                Yii::app()->end();			
            } 
	}
	
	public function ActionUpload()
	{
		if(isset($_GET['qqfile']))
		{
			$sessionID = Yii::app() -> getSession() -> getSessionID();
			
			$tempPath = realpath(Yii::app() -> basePath . '/../files') . '/temp/' . $sessionID;
			$fileName = $_GET['qqfile']; 
			
			$fileSize = 0;
			if (isset($_SERVER["CONTENT_LENGTH"])){
				$fileSize = (int)$_SERVER["CONTENT_LENGTH"];
			}
			
			if (!is_dir($tempPath)) {
				mkdir($tempPath);
			}
			
			$path = $tempPath . '/' . $fileName;
			
			$input = fopen("php://input", "r");
	        $temp = tmpfile();
	        $realSize = stream_copy_to_stream($input, $temp);
	        fclose($input);
	        	     
	        
	        $target = fopen($path, "w");        
	        fseek($temp, 0, SEEK_SET);
	        stream_copy_to_stream($temp, $target);
	        fclose($target);
			
	        echo CJSON::encode(array(
	        	'success' => 'true',
	        	'filename' => $path,
				'size' => $fileSize	        		        	
	        ));
		}
		else
		{
			 echo CJSON::encode(array(
	        	'success' => 'false',
	        	'error' => 'Has no file!'
	        ));
		}
	}
}